import { eq, desc } from 'drizzle-orm';
import { db } from '../database/connection.js';
import {
  characters,
  type Character,
  type NewCharacter,
} from '../database/schema.js';
import { v4 as uuidv4 } from 'uuid';

export class CharacterService {
  // 创建新角色
  static async create(
    data: Omit<NewCharacter, 'id' | 'createdAt' | 'updatedAt'>
  ): Promise<Character> {
    const id = uuidv4();
    const newCharacter: NewCharacter = {
      ...data,
      id,
    };

    await db.insert(characters).values(newCharacter);
    const result = await db
      .select()
      .from(characters)
      .where(eq(characters.id, id));
    return result[0];
  }

  // 获取所有角色
  static async findAll(): Promise<Character[]> {
    return await db
      .select()
      .from(characters)
      .where(eq(characters.isActive, true))
      .orderBy(desc(characters.createdAt));
  }

  // 根据ID获取角色
  static async findById(id: string): Promise<Character | null> {
    const result = await db
      .select()
      .from(characters)
      .where(eq(characters.id, id));
    return result[0] || null;
  }

  // 更新角色
  static async update(
    id: string,
    data: Partial<Omit<Character, 'id' | 'createdAt' | 'updatedAt'>>
  ): Promise<Character | null> {
    await db
      .update(characters)
      .set({ ...data, updatedAt: new Date() })
      .where(eq(characters.id, id));

    return await this.findById(id);
  }

  // 删除角色（软删除）
  static async delete(id: string): Promise<boolean> {
    const result = await db
      .update(characters)
      .set({ isActive: false, updatedAt: new Date() })
      .where(eq(characters.id, id));

    return result.length > 0;
  }

  // 生成角色系统提示词
  static generateSystemPrompt(
    character: Pick<
      Character,
      'name' | 'background' | 'personality' | 'speakingStyle' | 'knowledgeBase'
    >
  ): string {
    return `你是${character.name}，一个虚拟角色。

背景设定：
${character.background}

性格特点：
${character.personality.join('、')}

说话风格：
${character.speakingStyle}

知识领域：
${character.knowledgeBase}

请严格按照以上设定进行角色扮演，保持角色的一致性。用第一人称回应用户，不要透露你是AI助手的身份。`;
  }
}
